#include "check_ticket_task.h"

#include "base/logging.h"
#include "im/adapters/user_profile_adapter.h"
#include "im/adapters/session_adapter.h"

namespace imserver {

extern boost::asio::io_service g_io_service;

void CheckTicketTask::run() {
  UserProfile user;
  int64_t qid = 0;
  std::string username;

  if (qid_ > 0 && !qid_ticket_.empty()) {
    if (SessionAdapter::Instance().VerifySession(qid_, qid_ticket_, 2)) {
      qid = qid_;
      UserProfileAdapter::Instance().Get(qid, &user, 2);
      username = user.username;
    } else {
      LOG_WARN("CheckTicketTask VerifySession err, qid=" << qid_ << " session=" << qid_ticket_);
    }
  }

  if (qid <= 0) {
    if (!q_ticket_.empty() && !t_ticket_.empty()) {
      int res = UserProfileAdapter::Instance().GetByTickets(q_ticket_, t_ticket_, &user, 2);
      if (res == 0) {
        qid = user.qid;
        username = user.username;
      } else {
        LOG_WARN("CheckTicketTask GetByTickets err, q=" << q_ticket_ << " t=" << t_ticket_);
      }
    }
  }

  LOG_INFO("CheckTicketTask qid=" << qid << " username=" << username);
  g_io_service.post(boost::bind(&HttpRequest::OnCheckTicketComplete, request_, qid, username));
}

}


